<?php
namespace jy_peisong;
defined('BY_JYA') or exit('error');
/*
*/
class member extends \plugin{
	
	/*
		会员注册
	*/
	public function register($member=array()){
		$update=$member;
		if(!$member['uniacid']){
			$member['uniacid']=$_SESSION['uniacid'];
		}
		if(!$member['mid']){
			$member['mid']=$_SESSION['uid'];
		}
		
		if(!$member['createtime']){
			$member['createtime']=TIMESTAMP;
		}
		if(!$member['mid']){
			return error('配送员会员注册失败，缺少会员ID.');
		}
		$ispid=$this->get('member',array('mid'=>$member['mid'],'group_id'=>$member['group_id'],'uniacid'=>$_SESSION['uniacid']),array('id'));
		if($ispid){
			$this->update('member',$update,array('mid'=>$member['mid'],'group_id'=>$member['group_id'],'uniacid'=>$_SESSION['uniacid']));
			return $ispid['id'];
		}
		$this->insert('member',$member);
		return $this->insertid();
	}
	/*
		申请成为配送员
	*/
	public function apply_agent($pid,$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$apply=$this->get('apply',array('pid'=>$pid,'uniacid'=>$_SESSION['uniacid']));
		if($apply && !$apply['status']){
			exi('该配送点你已申请过了！','error');
		}
		if($apply['status']!=2){
			$new_apply=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$mid,
				'pid'=>$pid,
				'status'=>0,
				'createtime'=>TIMESTAMP,
			);
			$this->insert('apply',$new_apply);
			$apply_id=$this->insertid();
		}else{
			$this->update('apply',array('status'=>0),array('pid'=>$pid,'uniacid'=>$_SESSION['uniacid']));
			$apply_id=$apply['id'];
		}
		if(!$this->setting['become_check']){
			//配送员无需审核，此处自动审核
			$this->check_apply($apply_id,1);
		}
		return true;
	}
	/*
		审核配送员
	*/
	public function check_apply($apply_id,$status,$remark=''){
		if(!$apply_id || !$status){
			return;
		}
		$apply=$this->get('apply',array('id'=>$apply_id));
		if(!$apply){
			return;
		}
		$update=array(
			'status'=>$status,
			'complete_time'=>TIMESTAMP,
		);
		if($update['status']==1){
			//审核通过，修改会员状态，修改上线相关数据
			$member_update=array(
				'status'=>1,
			);
			$this->update('member',$member_update,array('id'=>$apply['pid'],'uniacid'=>$_SESSION['uniacid']));
			$this->model('notice')->notice_check_apply($apply);
		}else{
			$member_update=array(
				'status'=>$status,
			);
			$this->update('member',$member_update,array('id'=>$apply['pid'],'uniacid'=>$_SESSION['uniacid']));
			$update['remark']=$remark;
		}
		$this->update('apply',$update,array('id'=>$apply_id));
		return true;
	}
	/*
		禁用配送员
	*/
	public function stop_agent($agent_id){
		$this->update('member',array('stop'=>1),array('mid'=>$agent_id));
	}
	/*
		恢复配送员
	*/
	public function start_agent($agent_id){
		$this->update('member',array('stop'=>0),array('mid'=>$agent_id));
	}
}